import React, { ReactElement, useState, useEffect, useRef } from 'react'
import { Modal, Form, Select, FormInstance, message } from 'antd'
import { updateDefaultRole } from './ajax'
import { RoleShcema } from '@src/components/schema/role'
import { AccountSchema } from '@src/components/schema/account'
import { awaitWrap } from '@src/assets/js/tool'
const { Item } = Form
const { Option } = Select

function initRoleList (data: AccountSchema | null, setRoles: (v: RoleShcema[]) => void): void {
  if (data === null) {
    return undefined
  }
  setRoles(data.roles instanceof Array ? data.roles : [])
}

async function submitHandle (data: AccountSchema | null, roleid: string, hide: () => void): Promise<void> {
  if (data === null) {
    return undefined
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateDefaultRole(data.id as string, roleid))
  h()
  if (e === null) {
    hide()
  }
}

interface Props {
  visible: boolean
  hide: () => void
  data: AccountSchema | null
}

function Main ({ visible, hide, data }: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  const [roles, setRoles] = useState<RoleShcema[]>([])
  const [id, setId] = useState(data !== null ? data.id : '')
  useEffect(() => {
    initRoleList(data, setRoles)
    if (data !== null) {
      setId(data.roleid_default)
    }
    const c = ref.current
    if (c !== null && data !== null) {
      c.setFieldsValue({ id: data.roleid_default })
    }
  }, [data])
  useEffect(() => {
    const c = ref.current
    if (c !== null) {
      c.resetFields()
    }
  }, [])
  return (
    <Modal title='设置默认桌面' visible={visible} maskClosable={false} onCancel={hide} onOk={() => ref.current?.submit()}>
      <Form ref={ref} initialValues={{ id }} onFinish={async (d: {id: string}) => await submitHandle(data, d.id, hide)}>
        <Item name='id' label='默认桌面' rules={[{ required: true, message: '默认角色不能为空' }]}>
          <Select placeholder='请选择'>
            {roles.map(li => {
              return <Option value={li.id} key={li.id}>{li.name}</Option>
            })}
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
